package cn.senjoeson.triper.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;
import java.util.Random;

import butterknife.BindView;
import cn.senjoeson.mylibrary.utilschanged.MyToast;
import cn.senjoeson.triper.R;
import cn.senjoeson.triper.base.BaseActivity;
import cn.senjoeson.triper.base.GreenDaoManager;
import cn.senjoeson.triper.bean.HistoryBean;
import cn.senjoeson.triper.dao.HistoryBeanDao;
import cn.senjoeson.triper.fragment.SearchHistoryFragment;
import cn.senjoeson.triper.fragment.SearchListFragment;

/**
 * Created by senjoeson on 2018/1/1.
 */

public class SearchActivity extends BaseActivity implements TextView.OnEditorActionListener {

    public HistoryBeanDao mHistoryBeanDao;
    @BindView(R.id.goback_left)
    ImageView mGobackLeft;
    @BindView(R.id.et_search)
    AutoCompleteTextView mEtSearch;
    @BindView(R.id.search_layout)
    LinearLayout mSearchLayout;
    @BindView(R.id.search_container)
    FrameLayout mSearchContainer;
    public SearchHistoryFragment mSearchHistoryFragment;
    public SearchListFragment mSearchListFragment;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {
        mHistoryBeanDao = GreenDaoManager.getInstance().getNewSession().getHistoryBeanDao();
        //showHistory();
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        mSearchHistoryFragment = new SearchHistoryFragment();
        fragmentTransaction.add(R.id.search_container, mSearchHistoryFragment);
        fragmentTransaction.commit();


    }

    private void showHistory() {
/*
        */
    }

    @Override
    protected void initData() {
        //将数据写入数据库

    }

    @Override
    protected void initListener() {
        /*mFoodrink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AppUtils.getContext(), DinningListActivity.class);
                intent.putExtra("title", mFoodrink.getTitle());
                startActivity(intent);
            }
        });*/
        mGobackLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mEtSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        /*mEtSearch.addTextChangedListener(new SimpleTextChangeListener(){
            @Override
            public void afterTextChanged(Editable s) {
                String content = s.toString();

            }
        });*/
        mEtSearch.setOnEditorActionListener(this);

    }


    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH || event != null && event.getKeyCode() == KeyEvent.KEYCODE_SEARCH) {
            doQuery();
            // 当按了搜索之后关闭软键盘
            InputMethodManager systemService = (InputMethodManager) this.getSystemService(
                    Context.INPUT_METHOD_SERVICE);
            if (systemService != null) {
                systemService.hideSoftInputFromWindow(
                        SearchActivity.this.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
                return true;
            }
        }
        return false;
    }

    /**
     * 查询以前是否有记录
     *
     * @param
     */
    private void doQuery() {
        String content = mEtSearch.getText().toString().trim();
        //  MyToast.showToast("查询");
        if (TextUtils.isEmpty(content)) {
            MyToast.showToast("查询内容不能为空");
            return;
        }
        HistoryBean historyBean = new HistoryBean();
        historyBean.setContent(content);
        historyBean.setHistoryid(new Random().nextLong());
        historyBean.setCurrentSystemMills(System.currentTimeMillis());
        List<HistoryBean> list = mHistoryBeanDao.queryBuilder().where(HistoryBeanDao.Properties.Content.eq(content)).build().list();

        if (list != null && list.size() > 0) {
            HistoryBean bean = list.get(0);
            long historyid = bean.getHistoryid();
            mHistoryBeanDao.deleteByKey(historyid);
            mHistoryBeanDao.insert(historyBean);
        } else {
            mHistoryBeanDao.insert(historyBean);
        }
        showListFragment(content);

    }

    private void showListFragment(String content) {
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        if (mSearchListFragment == null) {
            getShowFragment(content, fragmentTransaction);
        } else {
            fragmentTransaction.remove(mSearchListFragment);
            getShowFragment(content, fragmentTransaction);
        }
        if (mSearchHistoryFragment != null) {

            fragmentTransaction.hide(mSearchHistoryFragment);
            fragmentTransaction.show(mSearchListFragment);
        }
        fragmentTransaction.commit();
    }

    private void getShowFragment(String content, FragmentTransaction fragmentTransaction) {
        mSearchListFragment = new SearchListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("content", content);
        mSearchListFragment.setArguments(bundle);
        fragmentTransaction.add(R.id.search_container, mSearchListFragment);
    }

    @Override
    public void onBackPressed() {
        if (mSearchHistoryFragment != null && mSearchHistoryFragment.isHidden()) {
            FragmentManager supportFragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
            fragmentTransaction.show(mSearchHistoryFragment);
            fragmentTransaction.hide(mSearchListFragment);
            fragmentTransaction.commit();
        } else {
            super.onBackPressed();
        }
    }
}
